package com.my.controller;

import com.google.gson.Gson;
import com.my.util.MailUtil;
import com.my.util.PhoneCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/code")
@CrossOrigin
@RestController
public class CodeController {
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/email")
    public String email(String email) {
        Map<String, String> map = new HashMap<>();
        try {
            MailUtil.send_mail(email);
            redisTemplate.opsForValue().set(email, MailUtil.getCode(), 5, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            e.printStackTrace();
            map.put("code", "500");
        }
        map.put("code", "200");
        return new Gson().toJson(map);
    }

    @RequestMapping("/phone")
    public String phone(String phone) {
        Map<String, String> map = new HashMap<>();
        PhoneCode.getPhonemsg(phone);
        redisTemplate.opsForValue().set(phone, PhoneCode.getCode(), 5, TimeUnit.MINUTES);
        map.put("code", "200");
        return new Gson().toJson(map);
    }
}
